package com.keyinong.caizhengting.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.keyinong.caizhengting.R;
import com.keyinong.caizhengting.tools.HttpTools;
import com.keyinong.caizhengting.tools.NetWorkUtil;
import com.keyinong.caizhengting.adapter.WelcomeViewPagerAdapter;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * @author：郑谦
 * @时间：2017-4-10 下午4:02:27
 * @类名：WelcomeActivity.java
 * @功能: 欢迎界面
 */

public class WelcomeActivity extends Activity {
    int time = 0;
    MyThread mThread;
    String phone;
    String pwd;
    private ImageView img_welcome;
    private ViewPager vp_welcome;
    private ArrayList<View> viewlist;
    private OnPageChangeListener pagechange = new OnPageChangeListener() {

        @Override
        public void onPageSelected(int arg0) {
            if (arg0 == viewlist.size() - 1) {
                FirstThread firstthread = new FirstThread();
                firstthread.start();
            }
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {

        }

        //状态改变的时候调用，arg0 =0什么都没做，arg0 =1正在滑动，arg0 =2滑动完毕
        @Override
        public void onPageScrollStateChanged(int arg0) {
//			//arg0
//			if (arg0 == viewlist.size()) {
//				FirstThread firstthread=new FirstThread();
//				firstthread.start();
//			}
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//			getWindow().addFlags(
//					WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_welcome);
        initRes();


    }

    private void initRes() {
        img_welcome = (ImageView) findViewById(R.id.img_welcome);
        vp_welcome = (ViewPager) findViewById(R.id.vp_welcome);
        SharedPreferences sp = getSharedPreferences("spuser",
                Context.MODE_PRIVATE);
        phone = sp.getString("phone", "");
        pwd = sp.getString("pwd", "");
        isfirst();
    }

    /**
     * 是否第一次进入app
     */
    private void isfirst() {
        SharedPreferences spfirst = getSharedPreferences("spWM",
                Context.MODE_PRIVATE);
        int first = spfirst.getInt("first", 0);
        if (first != 1) {
            windowWidth();
            vp_welcome.setVisibility(View.VISIBLE);
            img_welcome.setVisibility(View.GONE);
            LayoutInflater inflater = getLayoutInflater();
            View view1 = inflater.inflate(R.layout.item_welcome1, null);
            View view2 = inflater.inflate(R.layout.item_welcome2, null);
            View view3 = inflater.inflate(R.layout.item_welcome3, null);

            viewlist = new ArrayList<View>();
            viewlist.add(view1);
            viewlist.add(view2);
            viewlist.add(view3);
            Button btn_tiyan = (Button) view3.findViewById(R.id.btn_jinru);
            btn_tiyan.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.setClass(getApplicationContext(), LoginActivity.class);
                    startActivity(intent);
                    finish();
                }
            });
            WelcomeViewPagerAdapter adapter = new WelcomeViewPagerAdapter(
                    getApplicationContext(), viewlist);
            vp_welcome.setAdapter(adapter);
            vp_welcome.setOnPageChangeListener(pagechange);
        } else {
            vp_welcome.setVisibility(View.GONE);
            img_welcome.setVisibility(View.VISIBLE);
            mThread = new MyThread();
            mThread.start();
        }
    }

    /**
     * 登录
     */
    private void isLogin() {
        if (phone.equals("") || pwd.equals("")) {
            Intent intent = new Intent(getApplicationContext(),
                    LoginActivity.class);
            startActivity(intent);
            finish();
            return;
        }
        if (NetWorkUtil.isNetwork(WelcomeActivity.this) == false) {
            Toast.makeText(getApplicationContext(), "当前网络不可用", Toast.LENGTH_LONG).show();
            Intent intent = new Intent(getApplicationContext(),
                    LoginActivity.class);
            startActivity(intent);
            finish();
            return;
        }
        HttpTools httpTools = new HttpTools(getApplicationContext());
        httpTools.login(phone, pwd, new JsonLogin());
    }

    private void windowWidth() {
        WindowManager wManager = getWindowManager();
        Display display = wManager.getDefaultDisplay();
        int width = display.getWidth();
        int height = display.getHeight();
        SharedPreferences sp = getSharedPreferences("spWM",
                Context.MODE_PRIVATE);
        Editor editor = sp.edit();
        editor.putInt("first", 1);
        editor.putInt("width", width);
        editor.putInt("height", height);
        editor.commit();
    }

    private void intent() {
        Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
        startActivity(intent);
        finish();
    }

    private class MyThread extends Thread {
        @Override
        public void run() {
            super.run();
            try {
                MyThread.sleep(2 * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    isLogin();
                }
            });
        }

    }

    private class JsonLogin extends JsonHttpResponseHandler {

        @Override
        public void onSuccess(int statusCode, Header[] headers,
                              JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            try {
                boolean code = response.getBoolean("code");
                String msg = response.getString("msg");
                Log.i("zq", "login--" + response.toString());
                if (code == true) {
                    Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();

                    Intent intent = new Intent(getApplicationContext(),
                            FanqiedingcanActivity.class);
                    intent.putExtra("result", "Welcome");
                    startActivity(intent);
                    finish();
                } else {
                    Intent intent = new Intent(getApplicationContext(),
                            LoginActivity.class);
                    startActivity(intent);
                    finish();
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

    private class FirstThread extends Thread {

        @Override
        public void run() {
            super.run();
            try {
                FirstThread.sleep(2 * 1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
//					intent();
                }
            });
        }

    }

}